package com.wangtao.firstapp.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.wangtao.firstapp.R;
import com.wangtao.firstapp.adapters.CategoryClassAdapter;
import com.wangtao.firstapp.adapters.CategoryDetailsAdapter;
import com.wangtao.firstapp.adapters.HomeVPAdapter;
import com.wangtao.firstapp.custom.MyGridView;
import com.wangtao.firstapp.inter.OnCBCheckedChangeListener;
import com.wangtao.firstapp.inter.OnRVItemClickListener;
import com.wangtao.firstapp.inter.OnRVItemLongClickListener;
import com.wangtao.firstapp.modles.CategoryClassEntity;
import com.wangtao.firstapp.modles.CategoryDetailsData;
import com.wangtao.firstapp.utils.HttpUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 晒单页面  分类  二级页面
 * Created by lanouhn on 16/9/5.
 */
public class CategoryClassActivity extends AppCompatActivity implements OnCBCheckedChangeListener, OnRVItemClickListener, OnRVItemLongClickListener {
    private HorizontalScrollView horizontalscrollview;// 横向滑动的ScrollView
    private ImageView iv_back_titlebar;// 标题栏中的返回按钮
    private RecyclerView recyclerview_categoryclass;// 加载顶部的筛选框的ListView
    private CategoryClassEntity categoryClassEntity;// 顶部筛选框的实体类
    private CategoryClassAdapter categoryClassAdapter;// 顶部筛选框的适配器
    private ImageView iv_category_detail_list, iv_category_detail_grid;
    private TextView tv_showall_categoryclass, tv_showspecial_categoryclass;
    private List<CategoryDetailsData.DataBean> categoryDetailsData = new ArrayList<>();// 晒单 分类 二级 页面下 详细信息实体类
    private List<CategoryDetailsData.DataBean> datas = new ArrayList<>();
    private List<CategoryDetailsData.DataBean> datas1 = new ArrayList<>();
    private CategoryDetailsAdapter categoryDetailsAdapter;// 晒单 分类 二级 页面下 详细信息适配器
    // private MyGridView mygridview_categoryclass;
    private XRecyclerView xrecyclerview_categoryclass;
    private int type_id = 1;// 值为1时数据是精选，值为0时数据是全部
    private String idappend = "";
    private List<String> lists = new ArrayList<>();// 用于存放勾选的CheckBox里的ID
    int page = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_categoryclass);
        initView();

        GridLayoutManager gridLayoutManager = new GridLayoutManager(CategoryClassActivity.this, 2);
        xrecyclerview_categoryclass.setLayoutManager(gridLayoutManager);

        xrecyclerview_categoryclass.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xrecyclerview_categoryclass.setArrowImageView(R.drawable.ic_loading_rotate);
        xrecyclerview_categoryclass.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 0;

                getSpecialData();
            }

            @Override
            public void onLoadMore() {
                page++;

                getSpecialData();
            }
        });
        initEvent();
        getData();
        getSpecialData();
        // getAllData();
    }

    private void initView() {
        horizontalscrollview = (HorizontalScrollView) findViewById(R.id.horizontalscrollview);
        iv_back_titlebar = (ImageView) findViewById(R.id.iv_back_titlebar);// 标题栏返回按钮
        recyclerview_categoryclass = (RecyclerView) findViewById(R.id.recyclerview_categoryclass);
        iv_category_detail_list = (ImageView) findViewById(R.id.iv_category_detail_list);
        iv_category_detail_grid = (ImageView) findViewById(R.id.iv_category_detail_grid);
        tv_showall_categoryclass = (TextView) findViewById(R.id.tv_showall_categoryclass);// 标题栏  全部按钮
        tv_showspecial_categoryclass = (TextView) findViewById(R.id.tv_showspecial_categoryclass);// 标题栏 精选按钮
        // mygridview_categoryclass = (MyGridView) findViewById(R.id.mygridview_categoryclass);
        xrecyclerview_categoryclass = (XRecyclerView) findViewById(R.id.xrecyclerview_categoryclass);
        tv_showspecial_categoryclass.setTextColor(Color.BLACK);
    }

    private void initEvent() {
        // 标题栏中返回按钮
        iv_back_titlebar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        // 点击切换为GridView列表视图
        iv_category_detail_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        // 点击切换为ListView列表视图
        iv_category_detail_grid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        // 点击获取全部信息
        tv_showall_categoryclass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type_id = 0;
                tv_showall_categoryclass.setTextColor(Color.BLACK);
                tv_showspecial_categoryclass.setTextColor(Color.GRAY);
                getSpecialData();
            }
        });
        // 点击获取精选信息
        tv_showspecial_categoryclass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type_id = 1;
                tv_showall_categoryclass.setTextColor(Color.GRAY);
                tv_showspecial_categoryclass.setTextColor(Color.BLACK);
                getSpecialData();
            }
        });
    }

    // 解析晒单页面分类模块二级页面
    private void getData() {
        Intent intent = getIntent();
        String id = intent.getStringExtra("id");
        String url = "http://open4.bantangapp.com/category/categoryInfo";
        String param = "app_id=com.jzyd.BanTang&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=2559956&oauth_token=6beffa8c92276d19d3c23acb596024e6&track_deviceid=866962021116243&track_device_info=m1+note&channel_name=meizu&app_installtime=1471923362&app_versions=5.8.7&os_versions=5.1&screensize=1080&v=19&id=" + id;
        try {
            HttpUtils.doPostAsyn(url, param, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson = new Gson();
                    categoryClassEntity = gson.fromJson(result, CategoryClassEntity.class);
                    if (categoryClassEntity.getData().getSubclass_list().size() > 0) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 筛选后请求数据
    private void getDatas() {
        String url1 = "http://open4.bantangapp.com/community/post/listBySubclass";
        String param1 = "app_id=com.jzyd.BanTang&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=2559956&oauth_token=6beffa8c92276d19d3c23acb596024e6&track_deviceid=866962021116243&track_device_info=m1+note&channel_name=meizu&app_installtime=1471923362&app_versions=5.8.7&os_versions=5.1&screensize=1080&v=19&page=" + page + "&pagesize=10&ids=" + idappend + "&type_id=" + type_id;

        try {
            HttpUtils.doPostAsyn(url1, param1, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson1 = new Gson();
                    datas = gson1.fromJson(result, CategoryDetailsData.class).getData();
                    if (datas.size() > 0) {
                        handler.sendEmptyMessage(2);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取二级页面下精选的信息
    private void getSpecialData() {
        Intent intent_showspecial = getIntent();
        String showspecial_id = intent_showspecial.getStringExtra("id");
        String showspecialadd = "http://open4.bantangapp.com/community/post/listByCategory";
        String showspecialparam = "app_id=com.jzyd.BanTang&client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=2559956&oauth_token=6beffa8c92276d19d3c23acb596024e6&track_deviceid=866962021116243&track_device_info=m1+note&channel_name=meizu&app_installtime=1471923362&app_versions=5.8.7&os_versions=5.1&screensize=1080&v=19&page=" + page + "&pagesize=10&id=" + showspecial_id + "&type_id=" + type_id;
        try {
            HttpUtils.doPostAsyn(showspecialadd, showspecialparam, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson_special = new Gson();
                    datas = gson_special.fromJson(result, CategoryDetailsData.class).getData();
                    if (datas.size() > 0) {
                        handler.sendEmptyMessage(2);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    //  Toast.makeText(CategoryClassActivity.this, "网络访问失败", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(CategoryClassActivity.this, LinearLayoutManager.HORIZONTAL, false);
                    categoryClassAdapter = new CategoryClassAdapter(CategoryClassActivity.this, categoryClassEntity);
                    categoryClassAdapter.setOnCBCheckedChangeListener(CategoryClassActivity.this);
                    recyclerview_categoryclass.setAdapter(categoryClassAdapter);
                    recyclerview_categoryclass.setLayoutManager(linearLayoutManager);
                    break;
                case 2:
                    if (page == 0) {
                        categoryDetailsData.clear();
                        categoryDetailsData.addAll(datas);
                        categoryDetailsAdapter = new CategoryDetailsAdapter(CategoryClassActivity.this, categoryDetailsData);
                        xrecyclerview_categoryclass.setAdapter(categoryDetailsAdapter);
                        xrecyclerview_categoryclass.refreshComplete();
                        datas.clear();
                    } else {
                        categoryDetailsData.addAll(datas);
                        categoryDetailsAdapter.notifyDataSetChanged();
                        xrecyclerview_categoryclass.loadMoreComplete();
                        datas.clear();
                    }
                    categoryDetailsAdapter.setClickListener(CategoryClassActivity.this);
                    categoryDetailsAdapter.setLongClickListener(CategoryClassActivity.this);
                    break;
            }
        }
    };

    @Override
    public void OnCBCheckedChangeListener(final String ids, boolean isChecked) {
        if (isChecked) {// 判断CheckBox是否勾选
            lists.add(ids); // 把勾选的CheckBox的ID放进一个集合
            if (idappend.isEmpty()) {// 判断当做参数传递的idappend是否为空
                idappend = ids;// idappend为空时传进来的ids直接赋值给idappend
            } else {
                idappend = idappend + "%2C" + ids;// 如果idappend不为空就进行拼接
            }
        } else {// CheckBox没有被勾选时
            lists.remove(ids);// 删除集合里的ID参数
            idappend = "";// 将idappend置为null意思是查询全部
            if (lists.size() > 0) {// 当集合里有数据时遍历数组
                for (int i = 0; i < lists.size(); i++) {
                    if (i == 0) {// 当i=0时表示只勾选了一个筛选框
                        idappend = lists.get(i);// 此时获取数组里的元素传值解析即可
                    } else {
                        idappend = idappend + "%2C" + lists.get(i);// 拼接ID
                    }
                }
            } else {
                getSpecialData();// 当数据lists没有数据时,意为查询全部
                return;
            }
        }
        getDatas();
    }

    // 下方详细列表的点击事件
    @Override
    public void OnRVItemClickListener(int position) {
        Intent intent = new Intent(CategoryClassActivity.this, CategoryShowDetailsActivity.class);
        String id_item = categoryDetailsData.get(position).getId();
        intent.putExtra("itemid", id_item);
        startActivity(intent);
    }

    // 下方详细列表的点击事件
    @Override
    public void OnRVItemLongClickListener(int position) {
        Intent intent = new Intent(CategoryClassActivity.this, CategoryShowDetailsActivity.class);
        String id_item = categoryDetailsData.get(position).getId();
        intent.putExtra("itemid", id_item);
        startActivity(intent);
    }
}
